#!/bin/bash

# 割叶机PLC控制系统 - RK3588端部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 打印标题
print_header() {
    echo "======================================================================"
    echo -e "${BLUE}割叶机PLC控制系统 - RK3588端部署脚本${NC}"
    echo "======================================================================"
}

print_header

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    log_error "请使用sudo运行此脚本"
    exit 1
fi

# 步骤1：检查系统环境
log_step "1/6 检查系统环境..."

# 检查Python3
if ! command -v python3 &> /dev/null; then
    log_error "Python3未安装"
    log_info "正在安装Python3..."
    apt update
    apt install -y python3 python3-pip
fi
log_info "✅ Python3: $(python3 --version)"

# 检查pip3
if ! command -v pip3 &> /dev/null; then
    log_error "pip3未安装"
    log_info "正在安装pip3..."
    apt install -y python3-pip
fi
log_info "✅ pip3已安装"

# 步骤2：安装Python依赖
log_step "2/6 安装Python依赖..."

log_info "安装pymodbus..."
pip3 install pymodbus==3.5.2

log_info "安装pyserial..."
pip3 install pyserial

log_info "✅ Python依赖安装完成"

# 步骤3：检查硬件设备
log_step "3/6 检查硬件设备..."

# 检查串口设备
SERIAL_PORTS=("/dev/ttyS4" "/dev/ttyS1" "/dev/ttyUSB0")
FOUND_PORT=""

for port in "${SERIAL_PORTS[@]}"; do
    if [ -e "$port" ]; then
        FOUND_PORT="$port"
        log_info "✅ 找到串口设备: $port"
        break
    fi
done

if [ -z "$FOUND_PORT" ]; then
    log_warn "未找到标准串口设备"
    log_info "请插入USB转485设备后重新检查"
else
    # 设置串口权限
    chmod 666 "$FOUND_PORT"
    log_info "✅ 串口权限已设置"
fi

# 步骤4：设置文件权限
log_step "4/6 设置文件权限..."

if [ -f "rk3588_client.py" ]; then
    chmod +x rk3588_client.py
    log_info "✅ rk3588_client.py 权限已设置"
else
    log_error "rk3588_client.py 文件不存在"
    exit 1
fi

if [ -f "start.sh" ]; then
    chmod +x start.sh
    log_info "✅ start.sh 权限已设置"
else
    log_error "start.sh 文件不存在"
    exit 1
fi

# 步骤5：测试网络连接
log_step "5/6 测试网络连接..."

SERVER_IP="192.168.123.187"
if ping -c 1 $SERVER_IP &> /dev/null; then
    log_info "✅ 网络连接正常: $SERVER_IP"
else
    log_warn "⚠️  无法连接到服务器: $SERVER_IP"
    log_info "请检查网络配置："
    log_info "  1. RK3588 IP应在 192.168.123.x 网段"
    log_info "  2. Windows服务器IP: 192.168.123.187"
    log_info "  3. 确保两台设备在同一网络"
fi

# 步骤6：创建启动别名
log_step "6/6 创建启动别名..."

# 创建启动脚本的软链接
if [ ! -L "/usr/local/bin/start-plc" ]; then
    ln -s "$(pwd)/start.sh" /usr/local/bin/start-plc
    log_info "✅ 创建启动别名: start-plc"
fi

# 完成部署
echo "======================================================================"
log_info "🎉 RK3588端部署完成！"
echo "======================================================================"
echo
log_info "使用方法："
log_info "  方法1: sudo ./start.sh 192.168.123.187 9000"
log_info "  方法2: sudo start-plc 192.168.123.187 9000"
echo
log_info "部署检查清单："
log_info "  ✅ Python3环境"
log_info "  ✅ 依赖包安装"
if [ -n "$FOUND_PORT" ]; then
    log_info "  ✅ 串口设备: $FOUND_PORT"
else
    log_warn "  ⚠️  串口设备未检测到"
fi
log_info "  ✅ 文件权限设置"
if ping -c 1 $SERVER_IP &> /dev/null; then
    log_info "  ✅ 网络连接"
else
    log_warn "  ⚠️  网络连接异常"
fi
echo
log_info "下一步："
log_info "  1. 确保Windows端服务器已启动"
log_info "  2. 插入USB转485设备（如未插入）"
log_info "  3. 运行: sudo ./start.sh 192.168.123.187 9000"
echo
echo "======================================================================"
